package calculatorController;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;
import java.util.StringTokenizer;

import javax.swing.JButton;

import calculatorModel.Operation;
import calculatorView.CalculatorArea;

public class NumbButtons implements Observer {

	/**
	 * 
	 */

	private CalculatorArea area;
	private JButton[] buttons;
	private boolean updated;

	public NumbButtons(CalculatorArea area, JButton[] buttons,
			Operation operator) {
		super();
		this.area = area;
		this.buttons = buttons;
		// this.operator = operator;
		operator.addObserver(this);
		for (int i = 0; i < buttons.length; i++) {
			buttons[i] = new JButton();
			buttons[i].setText("" + i);
			buttons[i].setBackground(Color.GRAY);
			SettaNumbs(buttons[i]);
		}
	}

	public JButton[] getButtons() {
		return buttons;
	}

	public void setButtons(JButton[] buttons) {
		this.buttons = buttons;
	}

	private void SettaNumbs(JButton button) {
		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String espression = area.getArea().getText();
				StringTokenizer strtok = new StringTokenizer(espression, " ");
				int verifySeq = strtok.countTokens();
				if(verifySeq == 3){
					strtok.nextToken();
					strtok.nextToken();
					String token3 = strtok.nextToken();
					
				//TODO codice ripetuto
			
					if (((updated == true && verifySeq != 2) && token3.compareTo("-") != 0) | verifySeq > 3) {
						updated = false;
						area.getArea().setText(null);
						area.getArea().insert(e.getActionCommand(),
								area.getArea().getCaretPosition());
					} else {
						area.getArea().insert(e.getActionCommand(),
								area.getArea().getCaretPosition());
					}
				} else {
					if ((updated == true && verifySeq != 2) | verifySeq > 3) {
						updated = false;
						area.getArea().setText(null);
						area.getArea().insert(e.getActionCommand(),
								area.getArea().getCaretPosition());
					} else {
						area.getArea().insert(e.getActionCommand(),
								area.getArea().getCaretPosition());
					}
				}
			}
		});
	}

	@Override
	public void update(Observable o, Object arg) {
		updated = true;
		area.getArea().setText(null);

	}

}
